import os
import shutil
import tkinter as tk
from tkinter import filedialog, messagebox, TkVersion

def select_directory():
    """选择目录"""
    directory = filedialog.askdirectory()
    if directory:
        directory_var.set(directory)
        list_files(directory)

def list_files(directory):
    """列出目录中的文件"""
    file_list.delete(0, tk.END)
    for file_name in os.listdir(directory):
        file_list.insert(tk.END, file_name)

def batch_rename():
    """批量重命名文件"""
    directory = directory_var.get()
    if not directory:
        messagebox.showerror("错误", "请先选择一个目录！")
        return

    prefix = rename_prefix_var.get()
    if not prefix:
        messagebox.showerror("错误", "请输入重命名前缀！")
        return

    try:
        for idx, file_name in enumerate(os.listdir(directory), start=1):
            old_path = os.path.join(directory, file_name)
            if os.path.isfile(old_path):
                new_name = f"{prefix}_{idx}{os.path.splitext(file_name)[1]}"
                new_path = os.path.join(directory, new_name)
                os.rename(old_path, new_path)
        list_files(directory)
        messagebox.showinfo("成功", "文件重命名完成！")
    except Exception as e:
        messagebox.showerror("错误", f"重命名失败：{e}")

def batch_delete():
    """批量删除文件"""
    directory = directory_var.get()
    if not directory:
        messagebox.showerror("错误", "请先选择一个目录！")
        return

    try:
        for file_name in os.listdir(directory):
            file_path = os.path.join(directory, file_name)
            if os.path.isfile(file_path):
                os.remove(file_path)
        list_files(directory)
        messagebox.showinfo("成功", "文件删除完成！")
    except Exception as e:
        messagebox.showerror("错误", f"删除失败：{e}")

# 创建主窗口
root = tk.Tk()
root.title("批量文件处理工具")
root.geometry("600x600")
root.resizable(False, False)
root.title("tkinter GUI Example")
root.iconbitmap("email_64.ico")  # 设置窗口图标（需要提供图标文件）

# 目录选择
directory_var = tk.StringVar()
tk.Label(root, text="目标目录:").pack(pady=5)
tk.Entry(root, textvariable=directory_var, width=50).pack(pady=5)
tk.Button(root, text="选择目录", command=select_directory).pack(pady=5)

# 文件列表
tk.Label(root, text="文件列表:").pack(pady=5)
file_list = tk.Listbox(root, width=80, height=15)
file_list.pack(pady=5)

# 批量操作
rename_prefix_var = tk.StringVar()
tk.Label(root, text="重命名前缀:").pack(pady=5)
tk.Entry(root, textvariable=rename_prefix_var, width=20).pack(pady=5)
tk.Button(root, text="批量重命名", command=batch_rename, bg="green", fg="white").pack(pady=5)
tk.Button(root, text="批量删除", command=batch_delete, bg="red", fg="white").pack(pady=5)

# 启动主循环
root.mainloop()
